#!/usr/bin/env python
#coding=utf-8

#This file for nodemcu, maked by ZeroDay.
#Using this to automate the discovery procedure.
#Author: openthings@163.com. copyright&GPL V2.
#Last modified 2014-11-15.

import x_serial

#open file for read or write.
#filename: file to be opened, directories are not supported
'''  mode:
"r":  read mode (the default)
"w":  write mode
"a":  append mode
"r+": update mode, all previous data is preserved
"w+": update mode, all previous data is erased
"a+": append update mode, previous data is preserved, writing is only allowed at the end of file
'''
def fileopen(filename,mode):
	strResult = x_serial.xcmd2("file.open(\""+filename+"\",\"" + mode +"\")")
	return strResult

#write string to file.
def filewriteline(strline):
	strResult = x_serial.xcmd2("file.writeline(\'" + strline + "\')")
	return strResult

#closefile.
def fileclose():
	strResult = x_serial.xcmd2("file.flush()")
	strResult = x_serial.xcmd2("file.close()")
	return strResult

#Upload file to nodemcu.
#strFileName: host file.
#strScript: file on nodemcu.
def uploadfile(strFileName,strScript):
	fileopen(strScript,"w")
	print "=========================================="
	print "Uploading:",strFileName
	luafile = open(strFileName,'r')
	for  strlualine in  luafile: 
		print "#",strlualine
		strlualine = strlualine.strip('\n')
		strlualine = strlualine.replace("\\","\\\\")
		strlualine = strlualine.replace("\"","\\\"")
		print ">>>",strlualine
		strLast = filewriteline(strlualine)
	luafile.close()
	print "=========================================="
	fileclose()
	print "Upload Finished."

#Func：readline
def filereadline(filename):
	#strResult = x_serial.xcmd("file.readline(\""+filename+"\")")
	return strResult
	
#list all file.
def list():
	strResult = x_serial.xcmd("node.list()")
	return strResult

#delete all file.
def fileremoveall():
	#strResult = x_serial.xcmd2("node.format()")
	print "TODO:will remove all file."
	return strResult

#remove one file.
def fileremove(filename):
	strResult = x_serial.xcmd2("file.remove(\""+filename+"\")")
	return strResult

